package worker;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import result.ClassRequest;


public class RemoteClassLoader extends ClassLoader { 

	private int problemNumber;
	private int version;
	private ObjectOutputStream outStream;
	private ObjectInputStream  inStream;
	

	public RemoteClassLoader(int problemNumber, int version,
			ObjectOutputStream outStream, ObjectInputStream inStream) {
		super();
		this.problemNumber = problemNumber;
		this.version = version;
		this.outStream = outStream;
		this.inStream = inStream;
	}


	public RemoteClassLoader(ObjectOutputStream outStream, ObjectInputStream inStream) {
		this.outStream = outStream;
		this.inStream = inStream;
	}


	public void setProblemNumber(int problemNumber) {
		this.problemNumber = problemNumber;
	}


	public void setVersion(int version) {
		this.version = version;
	}


	@Override
	protected Class<?> findClass(String name) throws ClassNotFoundException {
		try {
			outStream.writeObject(new ClassRequest(problemNumber, version, name));	
			System.out.println("Ask for class " + name);
			byte[] classInfo = (byte[]) inStream.readObject();
			System.out.println("Got " + classInfo);
			return defineClass(name,classInfo, 0, classInfo.length);
		} catch (IOException e) {
			e.printStackTrace();
			throw new ClassNotFoundException(name + " - " + e.toString());
		}		
	}

	
}